package com.neuedu.security.service;

import com.neuedu.security.mapper.UserMapper;
import com.neuedu.security.model.RespBean;
import com.neuedu.security.model.Role;
import com.neuedu.security.model.User;
import com.neuedu.security.model.UserModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserService implements UserDetailsService {

    @Autowired
    UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        User user = userMapper.searchUserByUsername(s);
        if (user == null) {
            throw new UsernameNotFoundException("用户名或密码错误！");
        }
        // 查找用户对应的角色
        List<Role> roles = userMapper.searchRolesByUserId(user.getId());
        user.setRoles(roles);
        return user;
    }

    public List<UserModel> getUsers(String nameKeyWords) {
        return userMapper.getUsers(nameKeyWords);
    }

    public RespBean delUser(int id) {
        int num = userMapper.delUser(id);
        if (num == 0) {
            return RespBean.fail(500, "删除用户失败！");
        } else {
            return RespBean.success(200, "删除用户成功！");
        }
    }

    public RespBean updateStatus(UserModel user) {
        User securityUser = ((User) SecurityContextHolder.getContext().getAuthentication().getPrincipal());
        if (user.getId() == securityUser.getId()) {
            return RespBean.fail(500, "您现在是登录状态，不能修改自己的状态!");
        } else {
            int num = userMapper.updateStatus(user);
            if (num == 0) {
                return RespBean.fail(500, "更新状态失败！");
            } else {
                return RespBean.success(200, "更新状态成功！");
            }
        }
    }
}
